package org.dromara.common.mongo;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ChatMessageMongoDao {

    @Autowired
    private MongoOperations mongoOperations;

    private static String collectionName = "chat_message";



    public List<ChatMessage> getMessages(Long userId, String sessionId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("sessionId").is(sessionId));
        Sort sort = Sort.by(new Sort.Order(Sort.Direction.ASC, "time"));
        query.with(sort);
        return mongoOperations.find(query, ChatMessage.class, collectionName);
    }


    public List<ChatMessage> findMessage(Long userId, String messageId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("messageId").is(messageId));

        return mongoOperations.find(query, ChatMessage.class, collectionName);
    }


    public void saveOrUpdate(Long userId, ChatMessage chatMessage) {
        List<ChatMessage> messages = findMessage(userId, chatMessage.getMessageId());
        if (CollectionUtils.isEmpty(messages)) {
            chatMessage.setTime(LocalDateTime.now());
            chatMessage.setUserId(userId);

            mongoOperations.insert(chatMessage, collectionName);
        } else {
            Query query = new Query();
            query.addCriteria(Criteria.where("userId").is(userId));
            query.addCriteria(Criteria.where("messageId").is(chatMessage.getMessageId()));

            Update update = new Update();
            update.set("content", chatMessage.getContent());

            mongoOperations.updateMulti(query, update, collectionName);
        }
    }
}
